package com.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yz.common.R;
import com.yz.entity.Employee;
import com.yz.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @RequestMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        // 1.将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        // 2、根据云提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        log.info(employeeService.getOne(wrapper).toString());
        Employee emp = employeeService.getOne(wrapper);

        // 3、如果没有查询到则返回登录失败结果
        if(emp == null){
            return R.error("不存在该用户");
        }

        // 4、密码比对，如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误");
        }

        // 5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("员工已禁用");
        }

        // 6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出登录成功！");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> saveEmployee(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工，员工信息{}",employee);

        // 设置初始密码
        String password = DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8));
        employee.setPassword(password);

        // 设置创建时间和更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        // 设置创建者和更新者
//        employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
//        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employeeService.save(employee);
        return R.success("保存成功");
    }

    /**
     * 路由参数  根据id查询Employee
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getEmployee(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if(employee == null)
            return R.error("该id不存在！");
        return R.success(employee);
    }

    /**
     * 获取用户分页数据
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R<Page<Employee>> pageEmployee(Integer page,Integer pageSize,String name){
        Page<Employee> employeePage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(name),Employee::getUsername,StringUtils.trim(name));
        employeeService.page(employeePage,wrapper);
        return R.success(employeePage);
    }

    /**
     * admin管理员禁用员工
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> disabledEmployee(HttpServletRequest request,@RequestBody Employee employee){
        // 1、获取操作者的id，判断操作者是否为管理员，是管理员则可以继续操作，并返回已禁用员工，否则返回错误 你不是管理员，禁用员工失败
        Long id = (Long) request.getSession().getAttribute("employee");
        Employee byId = employeeService.getById(id);
        if(byId==null || !byId.getUsername().equals("admin")){
            return R.error("你不是管理员，禁用员工失败");
        }
        // 2、设置更改者，和更新时间
//        employee.setUpdateUser(byId.getId());
//        employee.setUpdateTime(LocalDateTime.now());
        // 3、执行更新操作 修改目标的status
        boolean b = employeeService.updateById(employee);
        if(b)
            return R.success("已禁用员工");

        return R.error("禁用员工失败");
    }


}
